package 行为型模式

import java.math.BigDecimal


/**
 * 使多个对象都有机会处理请求，从而避免请求的发送者和接收者之间的耦合关系。
 * 将这些对象连成一条链，并沿着这条链传递该请求，直到有一个对象处理它为止。
 */
data class Request(val name: String, val amount: Int)


interface Handler {
    val name: String
    fun process(request: Request): Boolean?
}

class ManagerHandler(override val name: String, private val amount: Int) : Handler {
    override fun process(request: Request): Boolean? {
        if (request.amount > this.amount) {
            return null
        }
        return request.name != "bob"
    }

}


class HandlerChain {
    private val handlers = ArrayList<Handler>()

    fun addHandler(handler: Handler): HandlerChain {
        handlers.add(handler)
        return this
    }

    fun process(request: Request): Boolean? {
        handlers.forEach { handler ->
            handler.process(request)?.let {
                println("$request ${if (it) "Approved by" else "Denied by"} ${handler.name}")
                return it
            }
        }
        return null
    }
}

fun main(args: Array<String>) {
    HandlerChain()
        .addHandler(ManagerHandler(name = "Manager1", amount = 500))
        .addHandler(ManagerHandler(name = "Manager2", amount = 5000))
        .process(Request(name = "John", amount = 1000))
}